/**
 *
 * @author ilya portnyagin iportnyagin@gmail.com
 */

package ru.portnyagin.helpdeskru.converter;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import ru.portnyagin.helpdeskru.model.Organization;
import ru.portnyagin.helpdeskru.service.OrganizationService;
import ru.portnyagin.helpdeskru.util.EJB;

    
@FacesConverter(forClass = Organization.class)
public class OrganizationConverter implements Converter {
    
    private OrganizationService organizationService = EJB.lookup(OrganizationService.class);
    
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null || value.length() == 0){
            return null;
        }

        Organization structPodr = organizationService.find(Long.valueOf(value));

        if (structPodr == null) {
            throw new ConverterException(new FacesMessage("Unknown Organization ID: " + value));
        }

        return structPodr;
    }
    
    
    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (!(value instanceof Organization) || ((Organization) value).getId() == null) {
            return null;
        }

        return ((Organization) value).getId().toString();
    }
    
    
    
    
    
}
